import { createStore } from 'vuex';
import { getAnswer, evaluateAnswer, resetSession, searchCases, searchWithOpenAI } from '../services/api';
import { isLoggedIn, getUserData, saveUserData, getCurrentUser } from '../services/auth';

export default createStore({
  state: {
    qaMessages: [
      {
        type: 'bot',
        content: '您可以输入法律相关问题，我会尽力提供专业解答。'
      }
    ],
    testMessages: [
      {
        type: 'bot',
        content: '请输入考试问题和您的答案，系统将为您评分。'
      }
    ],
    caseMessages: [
      {
        type: 'bot',
        content: '请输入案情描述，系统将为您提供两种模型的比较分析。'
      }
    ],
    // 模型比较结果
    modelComparisonResults: {
      ragflow: {
        content: '',
        isLoading: false
      },
      openai: {
        content: '',
        isLoading: false
      }
    },
    isLoading: false,
    // 用户认证状态
    auth: {
      isLoggedIn: false,
      currentUser: null
    }
  },
  mutations: {
    // 添加问答消息
    ADD_QA_MESSAGE(state, message) {
      state.qaMessages.push(message);
      // 登录状态下保存数据
      if (state.auth.isLoggedIn) {
        saveUserData('qaMessages', state.qaMessages);
      }
    },
    // 更新最后一条机器人消息
    UPDATE_LAST_BOT_QA_MESSAGE(state, content) {
      const lastBotMessage = [...state.qaMessages].reverse().find(msg => msg.type === 'bot');
      if (lastBotMessage) {
        lastBotMessage.content = content;
        // 登录状态下保存数据
        if (state.auth.isLoggedIn) {
          saveUserData('qaMessages', state.qaMessages);
        }
      }
    },
    // 添加测试消息
    ADD_TEST_MESSAGE(state, message) {
      state.testMessages.push(message);
      // 登录状态下保存数据
      if (state.auth.isLoggedIn) {
        saveUserData('testMessages', state.testMessages);
      }
    },
    // 更新最后一条机器人测试消息
    UPDATE_LAST_BOT_TEST_MESSAGE(state, content) {
      const lastBotMessage = [...state.testMessages].reverse().find(msg => msg.type === 'bot');
      if (lastBotMessage) {
        lastBotMessage.content = content;
        // 登录状态下保存数据
        if (state.auth.isLoggedIn) {
          saveUserData('testMessages', state.testMessages);
        }
      }
    },
    // 添加案例消息
    ADD_CASE_MESSAGE(state, message) {
      state.caseMessages.push(message);
      // 登录状态下保存数据
      if (state.auth.isLoggedIn) {
        saveUserData('caseMessages', state.caseMessages);
      }
    },
    // 更新最后一条机器人案例消息
    UPDATE_LAST_BOT_CASE_MESSAGE(state, content) {
      const lastBotMessage = [...state.caseMessages].reverse().find(msg => msg.type === 'bot');
      if (lastBotMessage) {
        lastBotMessage.content = content;
        // 登录状态下保存数据
        if (state.auth.isLoggedIn) {
          saveUserData('caseMessages', state.caseMessages);
        }
      }
    },
    // 重置问答消息
    RESET_QA_MESSAGES(state) {
      state.qaMessages = [
        {
          type: 'bot',
          content: '您可以输入法律相关问题，我会尽力提供专业解答。'
        }
      ];
      // 登录状态下保存数据
      if (state.auth.isLoggedIn) {
        saveUserData('qaMessages', state.qaMessages);
      }
    },
    // 重置案例消息
    RESET_CASE_MESSAGES(state) {
      state.caseMessages = [
        {
          type: 'bot',
          content: '请输入案情描述，系统将为您推荐相似案例和法律分析。'
        }
      ];
      // 登录状态下保存数据
      if (state.auth.isLoggedIn) {
        saveUserData('caseMessages', state.caseMessages);
      }
    },
    // 添加测试系统分隔线
    ADD_TEST_SEPARATOR(state) {
      state.testMessages.push({
        type: 'separator',
        content: '------- 新评测开始 -------'
      });
      state.testMessages.push({
        type: 'bot',
        content: '请输入考试问题和您的答案，系统将为您评分。'
      });
      // 登录状态下保存数据
      if (state.auth.isLoggedIn) {
        saveUserData('testMessages', state.testMessages);
      }
    },
    // 添加案例检索分隔线
    ADD_CASE_SEPARATOR(state) {
      state.caseMessages.push({
        type: 'separator',
        content: '------- 新检索开始 -------'
      });
      state.caseMessages.push({
        type: 'bot',
        content: '请输入案情描述，系统将为您推荐相似案例和法律分析。'
      });
      // 登录状态下保存数据
      if (state.auth.isLoggedIn) {
        saveUserData('caseMessages', state.caseMessages);
      }
    },
    // 设置加载状态
    SET_LOADING(state, isLoading) {
      state.isLoading = isLoading;
    },
    // 更新模型对比结果
    UPDATE_MODEL_RESULT(state, { model, content }) {
      state.modelComparisonResults[model].content = content;
    },
    
    // 设置模型加载状态
    SET_MODEL_LOADING(state, { model, isLoading }) {
      state.modelComparisonResults[model].isLoading = isLoading;
    },
    
    // 重置模型对比结果
    RESET_MODEL_COMPARISON(state) {
      state.modelComparisonResults = {
        ragflow: {
          content: '',
          isLoading: false
        },
        openai: {
          content: '',
          isLoading: false
        }
      };
    },
    
    // 设置用户认证状态
    SET_AUTH_STATE(state, { isLoggedIn, currentUser }) {
      state.auth.isLoggedIn = isLoggedIn;
      state.auth.currentUser = currentUser;
    },
    
    // 加载用户数据
    LOAD_USER_DATA(state) {
      if (!state.auth.isLoggedIn) return;
      
      // 加载问答消息
      const qaMessages = getUserData('qaMessages');
      if (qaMessages && qaMessages.length > 0) {
        state.qaMessages = qaMessages;
      }
      
      // 加载测试消息
      const testMessages = getUserData('testMessages');
      if (testMessages && testMessages.length > 0) {
        state.testMessages = testMessages;
      }
      
      // 加载案例消息
      const caseMessages = getUserData('caseMessages');
      if (caseMessages && caseMessages.length > 0) {
        state.caseMessages = caseMessages;
      }
      
      // 加载配置
      const config = getUserData('config');
      if (config) {
        // 这里可以加载用户的自定义配置
        console.log('加载了用户配置:', config);
      }
    }
  },
  actions: {
    // 初始化认证状态
    initAuth({ commit }) {
      const loggedIn = isLoggedIn();
      const currentUser = getCurrentUser();
      
      commit('SET_AUTH_STATE', { 
        isLoggedIn: loggedIn, 
        currentUser: currentUser 
      });
      
      if (loggedIn) {
        commit('LOAD_USER_DATA');
      }
    },
    
    // 发送问题并获取回答
    async sendQuestion({ commit }, question) {
      // 添加类型检查，确保question是字符串类型
      if (typeof question !== 'string') {
        console.error('sendQuestion: 期望字符串类型参数，但收到', typeof question);
        question = '';
      }
      
      if (!question.trim()) return;
      
      // 添加用户消息
      commit('ADD_QA_MESSAGE', { type: 'user', content: question });
      
      // 添加临时机器人消息（用于显示加载状态）
      commit('ADD_QA_MESSAGE', { type: 'bot', content: '思考中...' });
      commit('SET_LOADING', true);
      
      try {
        let currentAnswer = '';
        
        // 获取回答，使用onProgress回调实时更新UI
        const result = await getAnswer(question, (answer) => {
          currentAnswer = answer;
          commit('UPDATE_LAST_BOT_QA_MESSAGE', answer || '正在生成回答...');
        });
        
        // 最终更新消息内容
        commit('UPDATE_LAST_BOT_QA_MESSAGE', result.answer || currentAnswer || '无法获取回答');
      } catch (error) {
        commit('UPDATE_LAST_BOT_QA_MESSAGE', `发生错误: ${error.message}`);
      } finally {
        commit('SET_LOADING', false);
      }
    },
    
    // 提交测试评估
    async submitTest({ commit }, { question, answer }) {
      // 添加类型检查
      if (typeof question !== 'string' || typeof answer !== 'string') {
        console.error('submitTest: 期望字符串类型参数，但收到', { 
          questionType: typeof question, 
          answerType: typeof answer 
        });
        return;
      }
      
      if (!question.trim() || !answer.trim()) return;
      
      // 添加用户消息
      const userMessage = `**问题**：${question}\n\n**答案**：${answer}`;
      commit('ADD_TEST_MESSAGE', { type: 'user', content: userMessage });
      
      // 添加临时机器人消息（用于显示加载状态）
      commit('ADD_TEST_MESSAGE', { type: 'bot', content: '评估中...' });
      commit('SET_LOADING', true);
      
      try {
        let currentAnswer = '';
        
        // 获取评估，使用onProgress回调实时更新UI
        const result = await evaluateAnswer(question, answer, (answer) => {
          currentAnswer = answer;
          commit('UPDATE_LAST_BOT_TEST_MESSAGE', answer || '正在评估...');
        });
        
        // 最终更新消息内容
        commit('UPDATE_LAST_BOT_TEST_MESSAGE', result.answer || currentAnswer || '无法获取评估');
      } catch (error) {
        commit('UPDATE_LAST_BOT_TEST_MESSAGE', `发生错误: ${error.message}`);
      } finally {
        commit('SET_LOADING', false);
      }
    },
    
    // 案例检索
    async submitCaseSearch({ commit }, { description, type, year }) {
      // 添加类型检查
      if (typeof description !== 'string') {
        console.error('submitCaseSearch: 期望字符串类型参数，但收到', typeof description);
        return;
      }
      
      if (!description.trim()) return;
      
      // 构建用户消息，包含筛选条件
      let userMessage = `**案情描述**：${description}`;
      if (type) {
        userMessage += `\n\n**案件类型**：${type}`;
      }
      if (year) {
        userMessage += `\n\n**案件年份**：${year}`;
      }
      
      // 添加用户消息
      commit('ADD_CASE_MESSAGE', { type: 'user', content: userMessage });
      
      // 添加临时机器人消息（用于显示加载状态）
      commit('ADD_CASE_MESSAGE', { type: 'bot', content: '检索中...' });
      commit('SET_LOADING', true);
      
      try {
        let currentAnswer = '';
        
        // 获取案例检索结果，使用onProgress回调实时更新UI
        const result = await searchCases(description, type, year, (answer) => {
          currentAnswer = answer;
          commit('UPDATE_LAST_BOT_CASE_MESSAGE', answer || '正在检索相关案例...');
        });
        
        // 最终更新消息内容
        commit('UPDATE_LAST_BOT_CASE_MESSAGE', result.answer || currentAnswer || '未找到相关案例');
      } catch (error) {
        commit('UPDATE_LAST_BOT_CASE_MESSAGE', `发生错误: ${error.message}`);
      } finally {
        commit('SET_LOADING', false);
      }
    },
    
    // 重置会话
    async resetChat({ commit }) {
      commit('SET_LOADING', true);
      
      try {
        const result = await resetSession();
        commit('RESET_QA_MESSAGES');
        console.log(result.message);
      } catch (error) {
        console.error('重置会话失败:', error);
        // 尽管出错，仍然重置本地消息记录
        commit('RESET_QA_MESSAGES');
      } finally {
        commit('SET_LOADING', false);
      }
    },
    
    // 重置测试记录
    resetTestHistory({ commit }) {
      commit('ADD_TEST_SEPARATOR');
    },
    
    // 重置案例检索记录
    resetCaseHistory({ commit }) {
      commit('ADD_CASE_SEPARATOR');
    },
    
    // 使用双模型进行案例对比分析
    compareModels({ commit, state }, { prompt, filters }) {
      // Validate input
      if (!prompt || prompt.trim() === '') {
        console.error('Empty prompt provided');
        return;
      }

      // Add the user message to history
      commit('ADD_CASE_MESSAGE', {
        content: prompt,
        type: 'user'
      });

      // Reset previous results
      commit('RESET_MODEL_COMPARISON');
      
      // Set loading states
      commit('SET_MODEL_LOADING', { model: 'ragflow', loading: true });
      commit('SET_MODEL_LOADING', { model: 'openai', loading: true });
      
      // Construct the prompt with filters if any
      let enhancedPrompt = prompt;
      if (filters) {
        if (filters.caseType && filters.caseType !== '') {
          enhancedPrompt += `\n案件类型: ${filters.caseType}`;
        }
        if (filters.year && filters.year !== '') {
          enhancedPrompt += `\n年份: ${filters.year}`;
        }
      }
      
      // Call RAGFlow API
      searchCases(enhancedPrompt)
        .then(response => {
          commit('UPDATE_MODEL_RESULT', { 
            model: 'ragflow', 
            result: response.data || response 
          });
        })
        .catch(error => {
          console.error('RAGFlow API error:', error);
          commit('UPDATE_MODEL_RESULT', { 
            model: 'ragflow', 
            result: '无法获取RAGFlow结果: ' + (error.message || '未知错误') 
          });
        })
        .finally(() => {
          commit('SET_MODEL_LOADING', { model: 'ragflow', loading: false });
        });
      
      // Call OpenAI API
      searchWithOpenAI(enhancedPrompt)
        .then(response => {
          commit('UPDATE_MODEL_RESULT', { 
            model: 'openai', 
            result: response.data || response 
          });
        })
        .catch(error => {
          console.error('OpenAI API error:', error);
          commit('UPDATE_MODEL_RESULT', { 
            model: 'openai', 
            result: '无法获取OpenAI结果: ' + (error.message || '未知错误') 
          });
        })
        .finally(() => {
          commit('SET_MODEL_LOADING', { model: 'openai', loading: false });
        });
    }
  },
  getters: {
    qaMessages: state => state.qaMessages,
    testMessages: state => state.testMessages,
    caseMessages: state => state.caseMessages,
    modelComparisonResults: state => state.modelComparisonResults,
    isLoading: state => state.isLoading,
    isLoggedIn: state => state.auth.isLoggedIn,
    currentUser: state => state.auth.currentUser
  }
}); 